<?php
namespace Com\Pay;

class LvyiPay{

    private $config = array();
    private $allparam =array(); //所有提交的参数
    private $sign;

    public function __construct($mchData){
        $this->config = $mchData;
    }

    /*生成支付连接*/
    public function getUrl($order_info){
        $merchantCode = $this->config['mch_id'];
        $notifyUrl = S_URL . '/Api/NotifyCallback/LvyiPayNotify';
        $order_sn = $order_info['ordernumber'];
        $price = $order_info['paymoney'] * 100;
        $postdata = array(
               'transCode'     => '001',
               // 'service'    => '0002', //0002微信扫描
               'service'       => $order_info['service'], //0002微信扫描
               'transAmount'   => $price ,  //元转成分
               'bgReturnUrl'   => $notifyUrl,
               'reqDate'       => date('Ymd'),
               'reqTime'       => date('His'),
               'customerNo'    => $merchantCode,
               'externalId'    => $order_sn,
               'requestIp'     => get_client_ip(),
            );
        $url = 'http://channel.aigopay.cn/agent/transReq.action';
        $this->setParam($postdata);
        $postdata=$this->allparam;
        $resjson=$this->postJson($url,json_encode($postdata));
        $res = json_decode($resjson,true);
        return $res;
    }

    //回调方法，把返回数据处理成统一规定返回
    public function response(){
        $getdata = file_get_contents('php://input', 'r');
        $res = json_decode($getdata,true);
        if($res['code']==00 && $res['externalId']){

            //验证签名
            $this->setParam($res);
            if($this->sign !=$res['sign']){
                return false;
            }
            return true;

//            $r['other_order_number'] = $res['seqno'];
//            //订单号
//            $r['order_number'] = $res['externalId'];
//            $r['money'] = $res['amount'];
        }else{
            return false;
        }
    }

    private function gbkToUtf8($arr){
        if(is_array($arr)){
            $res = array();
            foreach($arr as $k => $v){
                $res[$k] = $this->gbkToUtf8($v);
            }
            return $res;
        }else{
            return mb_convert_encoding ( $arr, "UTF-8", "GBK" );
        }
    }

    /**
     * 对数组排序
     * @param $para 排序前的数组
     * return 排序后的数组
     */
    private function argSort($para)
    {
        ksort($para);
        reset($para);
        return $para;
    }
    private function setParam($param){
        $param=$this->argSort($param);
        $str = "";
        foreach($param as $key=>$val){
            if($key!='sign'){
                $str.=$key."=".$val."&";
            }
        }
        $str.='key='.$this->config['mch_key'];
        // echo $str;exit;
        $sign=md5($str);
        $sign=strtoupper($sign);
        $param['sign']=$sign;
        $this->sign=$sign;
        $this->allparam=$param;

    }

    private function postJson($url,$data){
        //echo '<br/>提交URL：'.$url.'<br/>';
        //echo '<br/>提交数据：<br/>';
        //print_r($data); //exit();

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data))
        );

        $result = curl_exec($ch);
        curl_close($ch);
        
        //echo '<br/>返回：<br/>';
        //print_r($result); //exit();
    
        return $result;
    }


}
